package org.lanqiao.music.web.interceptor;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.lanqiao.music.common.utils.Result;
import org.lanqiao.music.system.utils.JWTUtil;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/*
登录拦截器，判断是否有token是否合法
非法返回错误信息，否则放行
 */
@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException {
        System.out.println("=====通过拦截器=====");
        //获取token
        String token = request.getHeader("Authorization");

        System.out.println("拦截器返回的token"+token);
        //解决乱码
        response.setContentType("application/json;charset=utf-8");
        ObjectMapper objectMapper = new ObjectMapper();
        Result result=null;
        if (token == null || token.isEmpty()){
            PrintWriter out = response.getWriter();
            result=Result.fail(5101,"token 为空");
            //把对象转变为json返回给前端页面
            out.print(objectMapper.writeValueAsString(result));
            out.flush();
            return false;
        }
        if(!token.startsWith("Bearer ")){
            PrintWriter out = response.getWriter();
            result=Result.fail(5102,"token 开头不匹配");
            out.print(objectMapper.writeValueAsString(result));
            out.flush();
            return false;
        }
        token = token.replace("Bearer ","");
        System.out.println("拦截器返回的token"+token);
        if (!JWTUtil.verify(token)){
            PrintWriter out = response.getWriter();
            result=Result.fail(5103,"token 不正确");
            out.print(objectMapper.writeValueAsString(result));
            out.flush();
            return false;
        }
        return true;
    }

}
